package com.gree.syq.wifidemo;

import android.app.Activity;
import android.app.GreeWifiAccountPasswordManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.SWifi;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;

public class RemoteRole extends DemoRole {
    private final static String TAG = "RemoteRole";
    private WifiManager mWifiManager;
    private NotificationManager mNotificationManager;

    private static RemoteRole sRemoteState= null;
    private WifiP2pDeviceList mPeers = new WifiP2pDeviceList();
    private SWifi mSWifi;
    private Context mContext;

    private GreeWifiAccountPasswordManager mGreeWifiAccountPasswordManager;

    private String mMsg = "Aircondition";
    private boolean state = true;

    private Button buttonUp;
    private Button buttonDown;

    private Activity activity;

    private Handler mHandler = new Handler();
    private HandlerThread mHandlerThread = new HandlerThread("Remote");
    private Handler mStateHandler;
    private final int mKeepSecond = 15;

    private static class doSomeThing {
        private doSomeThing() {

        }

        public static final int GET_DEVICE_STATE = 0;
        public static final int CONFIG_NETWORK = 1;
        public static final int REFRESH_DEVICE_STATE = 2;

    }

    private DemoState mState = new DemoState() {
        @Override
        public void run(Message msg) {
            mState = mIdleState;
        }
    };

    private DemoState mIdleState = new DemoState() {
        @Override
        public void run(Message msg) {
            switch (msg.what) {
                case doSomeThing.REFRESH_DEVICE_STATE:
                    refreshDeviceList();
                    break;
                case doSomeThing.GET_DEVICE_STATE:
                    onRefreshDevice(msg.getData().getInt("state",0)
                            ,msg.getData().getInt("addr",0));
                    break;
                 case doSomeThing.CONFIG_NETWORK:
                     configNetwork();
                     break;
                default:
                    break;
            }
        }
    };

    public class cDeviceState {
        public int state;
        public int addr;
        public int keep;
    }

    ConcurrentHashMap<Integer,cDeviceState> mDeviceMap = new ConcurrentHashMap<>();

    Runnable deviceKeep = new Runnable() {
        @Override
        public void run() {
            for(Map.Entry<Integer,cDeviceState> entry: mDeviceMap.entrySet())
            {
                cDeviceState deviceState = entry.getValue();
                deviceState.keep = deviceState.keep - 1;
                if(deviceState.keep > 0){
                    mDeviceMap.put(entry.getKey(),deviceState);
                } else {
                    mDeviceMap.remove(entry.getKey());
                }
            }
            mStateHandler.postDelayed(deviceKeep,1000);
        }
    };


    public static RemoteRole getInstance(Context context) {
        if(sRemoteState == null) {
            sRemoteState = new RemoteRole(context);
        }
        return sRemoteState;
    }

    protected RemoteRole(Context context) {
        mContext = context;
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if("GREE".equals(android.os.Build.BRAND)) {
            mGreeWifiAccountPasswordManager = new GreeWifiAccountPasswordManager(context);
        }
        mHandlerThread.start();
        mStateHandler = new Handler(mHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                mState.run(msg);
            }
        };
    }



    @Override
    public void init(Activity activity) {
        this.activity = activity;
        mState = mIdleState;
        buttonUp = (Button) activity.findViewById(R.id.remoteButton);
        buttonDown = (Button) activity.findViewById(R.id.ariconditionButton);
        buttonUp.setText("探测设备");
        buttonUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mStateHandler.sendEmptyMessage(doSomeThing.REFRESH_DEVICE_STATE);
                DemoLog.getInstance().logi("开始探测设备");
            }
        });


        buttonDown.setText("进行配网");
        buttonDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mStateHandler.sendEmptyMessage(doSomeThing.CONFIG_NETWORK);
                DemoLog.getInstance().logi("开始配网");
            }
        });
        if("GREE".equals(android.os.Build.BRAND)) {
            buttonDown.setEnabled(true);
        } else {
            buttonDown.setEnabled(false);
        }
    }

    @Override
    public void init() {
        mStateHandler.post(deviceKeep);
    }

    @Override
    public void run(String para) {

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {

        } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {

            // request available peers from the wifi p2p manager. This is an
            // asynchronous call and the calling activity is notified with a
            // callback on PeerListListener.onPeersAvailable()
            mPeers = (WifiP2pDeviceList) intent.getParcelableExtra(
                    WifiP2pManager.EXTRA_P2P_DEVICE_LIST);
            for(WifiP2pDevice device : mPeers.getDeviceList()) {
                Log.d(TAG, "P2P peers changed: " + device.deviceName);
                DemoRole.doCommand(device.deviceName);
            }
        } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {


        } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {


        } else if (CONNECTIVITY_ACTION.equals(action)) {
            if(!"GREE".equals(android.os.Build.BRAND)) {
                return;
            }

            if(mWifiManager.getConnectionInfo() != null) {
                mSWifi = mGreeWifiAccountPasswordManager.ReadConnetingWifiInfo();
                if(mSWifi != null) {
                    String name = mSWifi.getSsid() + "/" + mSWifi.getPwd() + "/" + mSWifi.getEncryptionMode();
                    int type = 0;
                    switch(mSWifi.getEncryptionMode()) {
                        case "NONE" :
                            type = 0;
                            break;
                        case "WPA-PSK" :
                            type = 1;
                            break;
                        case "WPA-EAP" :
                            type = 2;
                            break;
                        default:
                            break;
                    }
                    MessageP2P.getInstance(mContext).sendNetworkCommand(mSWifi.getSsid(),mSWifi.getPwd(),type);
                }
            }
        }
    }

    public void refreshDeviceList() {
        MessageP2P.getInstance(mContext).sendRefreshCommand();
    }

    public void configNetwork() {
        state = true;
        if(mWifiManager.getConnectionInfo() != null) {
            mSWifi = mGreeWifiAccountPasswordManager.ReadConnetingWifiInfo();
            if(mSWifi != null) {
                int type = 0;
                switch(mSWifi.getEncryptionMode()) {
                    case "NONE" :
                        type = 0;
                        break;
                    case "WPA-PSK" :
                        type = 1;
                        break;
                    case "WPA-EAP" :
                        type = 2;
                        break;
                    default:
                        break;
                }
                MessageP2P.getInstance(mContext).sendNetworkCommand(mSWifi.getSsid(),mSWifi.getPwd(),type);
                mNotificationManager.cancelAll();
            }
        }
    }

    @Override
    public void unRegister() {
        super.unRegister();
        state = false;
    }

    public void onRefreshDeviceNative(int deviceState,int deviceAddr) {
        cDeviceState device = new cDeviceState();
        device.state = deviceState;
        device.addr = deviceAddr;
        device.keep = mKeepSecond;

        if(mDeviceMap.get(device.addr) != null) {
            if(mDeviceMap.get(device.addr).state == device.state) {
                mDeviceMap.put(device.addr,device);
                return;
            }
        }
        mDeviceMap.put(device.addr,device);


        Message msg = mStateHandler.obtainMessage(doSomeThing.GET_DEVICE_STATE);
        Bundle bundle = new Bundle();
        bundle.putInt("state",device.state);
        bundle.putInt("addr",device.addr);
        msg.setData(bundle);
        mStateHandler.sendMessage(msg);
    }

    private void onRefreshDevice(int deviceState,int deviceAddr){
        switch (deviceState) {
            case 0:
                sendNotify(deviceAddr,"发现一个未联网设备",View.INVISIBLE);
                DemoLog.getInstance().logi("发现一个未联网设备");
                break;
            case 1:
                sendNotify(deviceAddr,"发现一个可以配网设备",View.VISIBLE);
                DemoLog.getInstance().logi("发现一个可以配网设备");
                break;
            case 2:
                sendNotify(deviceAddr,"发现一个已联网设备",View.INVISIBLE);
                DemoLog.getInstance().logi("发现一个已联网设备");
                break;
            default:
                break;
        }

    }

    private void sendNotify(int id,String note,int showButton){
        mNotificationManager.cancel(id);

        RemoteViews mRemoteViews = new RemoteViews(RemoteRole.class.getPackage().getName(), R.layout.notification);
        mRemoteViews.setTextViewText(R.id.notiText,note);
        Intent buttonIntent = new Intent("com.gree.syq.wifidemo.CONFIG_NETWORK" );
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext,id,buttonIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.notiButton,pendingIntent);
        mRemoteViews.setViewVisibility(R.id.notiButton,showButton);

        Notification notification = new Notification.Builder(mContext)
                .setContent(mRemoteViews)
                .setDefaults(Notification.DEFAULT_ALL)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .build();

        mNotificationManager.notify(id,notification);
    }
}
